﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TidyBlog.Data
{
    /// <summary>
    /// INSERT命令生成类
    /// </summary>
    public class InsertCommand : Command
    {
        /// <summary>
        /// 插入的列
        /// </summary>
        protected List<ColumnValuePair> Columns;
        /// <summary>
        /// 是否获取新记录的编号
        /// </summary>
        protected bool IsSelectLastId = false;


        public InsertCommand(string table)
            : base(table)
        {

        }

        public InsertCommand(string[] tables)
            : base(tables)
        {

        }


        /// <summary>
        /// 指定插入的字段
        /// </summary>
        /// <param name="columns">字段</param>
        /// <returns>当前命令</returns>
        public InsertCommand Values(IEnumerable<ColumnValuePair> columns)
        {
            if (columns != null)
            {
                Columns = new List<ColumnValuePair>(columns);
            }

            return this;
        }

        /// <summary>
        /// 获取字段字符串
        /// </summary>
        /// <param name="isValue">是否字段值字符串</param>
        /// <returns>字段字符串</returns>
        protected string GetColumnString(bool isValue)
        {
            var result = new StringBuilder();
            var quote = DbHelper.Provider.QuoteSymbol;
            var paramPrefix = DbHelper.Provider.ParamPrefix;

            foreach (var column in Columns)
            {
                if (result.Length > 0)
                {
                    result.Append(",");
                }

                if (isValue)
                {
                    if (column.IsParamValue)
                    {
                        result.Append(paramPrefix);
                    }
                    result.Append(column.Value);
                }
                else
                {
                    result.Append(String.Format(quote, column.Name));
                }
            }

            return result.ToString();
        }

        /// <summary>
        /// 指定是否获取新记录的自动编号
        /// </summary>
        /// <param name="isSelectLastId">是否获取新记录的自动编号</param>
        /// <returns></returns>
        public InsertCommand SelectLastId(bool isSelectLastId)
        {
            IsSelectLastId = isSelectLastId;

            return this;
        }

        /// <summary>
        /// 生成SQL命令字符串
        /// </summary>
        /// <returns>SQL命令字符串</returns>
        public override string ToString()
        {
            var result = String.Format(DbHelper.Provider.GetCmdTemplate("CREATE"),
                GetTableString(), GetColumnString(false), GetColumnString(true)
            );

            return IsSelectLastId ? result + ";" + DbHelper.Provider.GetCmdTemplate("LAST_INSERT_ID") : result;
        }
    }
}
